package com.ymt.bpm.service.platform.profile.impl;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.appboot.env.Caches;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.model.PTenant;
import com.ymt.bpm.service.platform.cache.CacheService;
import com.ymt.bpm.service.platform.profile.TenantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class TenantServiceImpl implements TenantService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Autowired
    private CacheService cacheService;

    @Override
    //@Cacheable(cacheNames= Caches.TENANT, key="#tenantId")
    public JSONObject getTenantConf(String tenantId) {

        if (log.isDebugEnabled()) {
            log.debug("getTenantConf tenantId=" + tenantId);
        }
        if (tenantId==null) {
            tenantId = "0";
        }

        String cacheKey = cacheService.asKey(Caches.TenantPrefix.CFG.name(), tenantId);
        JSONObject rtn = cacheService.get(Caches.TENANT, cacheKey);

        if (rtn==null) {
            PTenant tenant = dao.selectOne("PTenantMapper", "selectByPrimaryKey", Integer.parseInt(tenantId));
            rtn = new JSONObject();
            if (tenant==null) {
                rtn.put("clazz", 1);
                return rtn;
            }
            String confStr = tenant.getCfg();
            if (confStr!=null) {
                rtn = JSONObject.parseObject(confStr);
            }
            rtn.put("clazz", tenant.getClazz());

            if (rtn!=null) {
                cacheService.put(Caches.TENANT, cacheKey, rtn);
            }
        }

        return rtn;
    }

    @Override
    public JSONObject initCfgByClazz(String clazz) {
        JSONObject rtn = new JSONObject();
        switch (clazz) {
            case "0":
                break;
            case "1":
                rtn.put("account", 100);
                rtn.put("attachment-enabled", true);
                break;
            case "2":
                rtn.put("account", 10000);
                rtn.put("attachment-enabled", true);
                break;
            default:
                rtn.put("account", 20);
        }
        return rtn;
    }

}
